package com.example.dbutils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * DataTable 对象
 * 
 * @author Jianpeng Tong
 * @since 2009-5-12
 * @version 1.0
 * */
public class DataTable {
	private Object[] dt = null;
	private ArrayList<Object[]> dataSet = new ArrayList<Object[]>();

	private int columnCount = 1;
	private int rowCount = 1;
	private int currentRow = 1;
	private boolean hasNext = true;

	public DataTable(ResultSet rs) {
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			columnCount = rsmd.getColumnCount();
			ArrayList<Object> header = new ArrayList<Object>();
			header.add(0, "rowid");
			for (int i = 1; i < columnCount; i++) {
				header.add(i, rsmd.getColumnLabel(i));
			}
			Object[] T = header.toArray();
			dataSet.add(T);
			int rowid = 1;
			while (rs.next()) {
				ArrayList<Object> row = new ArrayList<Object>();// 创建行

				row.add(0, String.valueOf(rowid));// 设置行号

				// 为行的各字段赋值
				for (int i = 1; i < columnCount; i++) {
					row.add(i, rs.getString(i));
				}

				dataSet.add(row.toArray());// 将行添加到表
				rowid++;
			}
			rowCount = dataSet.size();
			dt = dataSet.toArray();
			currentRow = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取总列数
	 * */
	public int getColumnCount() {
		return columnCount;
	}

	/**
	 * 获取当前行索引
	 * */
	public int getCurrentRow() {
		return currentRow;
	}

	/**
	 * 根据索引获取行
	 * */
	public String[] getRow(int rowIndex) {
		return (String[]) dt[rowIndex];
	}

	/**
	 * 获取总行数
	 * */
	public int getRowCount() {
		return rowCount;
	}

	/**
	 * 获取具有指定行索引及列索引字段信息
	 * 
	 * @param rowIndex
	 *            行索引
	 * @param columnIndex
	 *            列索引
	 * */
	public String getValue(int rowIndex, int columnIndex) {
		Object[] T = (Object[]) dt[rowIndex];
		return (String) T[columnIndex];
	}

	/**
	 * 获取具有指定行索引及列名称的字段信息
	 * 
	 * @param rowIndex
	 *            行索引
	 * @param columnName
	 *            列名称
	 * */
	public String getValue(int rowIndex, String columnName) {
		Object[] T = (Object[]) dt[0];
		int columnIndex = -1;
		for (int i = 0; i < columnCount; i++) {
			if (T[i].toString().compareToIgnoreCase(columnName) == 0)
				columnIndex = i;
		}
		if (columnIndex == -1)
			return null;
		else {
			T = (Object[]) dt[rowIndex];
			return (String) T[columnIndex];
		}
	}

	/**
	 * 是否存在下一行
	 * */
	public boolean hasNext() {
		if (currentRow >= rowCount) {
			hasNext = false;
		} else {
			hasNext = true;
		}
		return hasNext;
	}

	/**
	 * 获取下一行
	 * */
	public Object[] Next() {
		Object[] dr = (Object[]) dt[currentRow];
		currentRow += 1;
		return dr;
	}

	/**
	 * 设置指定行为当前行
	 * 
	 * @param currentRow
	 *            行索引
	 * */
	public void setCurrentRow(int currentRow) {
		this.currentRow = currentRow;
	}
}
